//
//  ClaimBankInfoViewController.m
//  MemberProject
//
//  Created by vincent luo on 15/7/17.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "ClaimBankInfoViewController.h"
#import "SelfClaimTableViewCell.h"
#import "SignInfoViewController.h"
#import "CityFileManager.h"
#import "ChoiceBankViewController.h"
#import "ClaimProgressViewController.h"
#import "ClaimPicViewController.h"
#import "IQKeyboardManager.h"
@interface ClaimBankInfoViewController ()
@property (nonatomic,strong) NSArray *titleArr;
@property (nonatomic,strong) NSMutableArray *contentArr;
@property (nonatomic,strong) NSArray *picArr;
@property (nonatomic,strong) NSMutableArray *bankArr;
@property (nonatomic,strong) NSMutableArray *branchArr;
@property (nonatomic,strong) NSArray *keyArr;

//@property (nonatomic,assign) NSInteger pickStyle;
@property (nonatomic,assign) NSInteger branchBankNo;

@property (nonatomic,strong) NSMutableDictionary *infoDic;

@property (nonatomic,strong) UITextField *editingField;

@end

@implementation ClaimBankInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.mainTableView registerNib:[UINib nibWithNibName:@"SelfClaimTableViewCell" bundle:nil] forCellReuseIdentifier:@"CellIdentifier"];
    self.title = @"自助申请";
    [self setupView];
    
    [self setupBankData];
    
    [self setupData];
}

-(void)setupBankData
{
    self.bankArr = [[NSMutableArray alloc]init];
    __block CSVoidBlock getLocalBlock = ^(void)
    {
        
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"bank" ofType:@"plist"];
        NSArray *data = [[NSArray alloc] initWithContentsOfFile:plistPath];
        for (int i=0; i<data.count; i++) {
            NSDictionary *dic = data[i];
            [self.bankArr addObject:dic];
        }
    };
    
    
    NSArray *arr = [[CityFileManager sharedManager]getLocalLog:BankFileType];
    if (arr==nil||[arr isKindOfClass:[NSNull class]]||arr.count==0) {
            [SVProgressHUD showWithStatus:@"加载银行信息" maskType:SVProgressHUDMaskTypeBlack];
                [[CityFileManager sharedManager]getBankFile:^(id result) {
                    NSArray *resultArr = result;
                    
                    if (result&&[result isKindOfClass:[NSArray class]]&&resultArr.count>0) {
                        [self.bankArr addObjectsFromArray:result];
                    }else
                    {
                        getLocalBlock();
                    }
                    [SVProgressHUD dismiss];
                } andDefault:^{
                    [SVProgressHUD dismiss];
                    getLocalBlock();
                }];
    }else
    {
        [self.bankArr addObjectsFromArray:arr];
    }

    
    
    
    
}

-(void)initInfoDic
{
    self.infoDic= [[NSMutableDictionary alloc]init];
    self.infoDic[@"accountName"]=[UserInfoManager sharedManager].userClaimInput.bankAccountName;
    
    self.infoDic[@"bankAccount"]= [UserInfoManager sharedManager].userClaimInput.bankAccount;
    
    self.infoDic[@"address"] = [UserInfoManager sharedManager].userClaimInput.bankAccountCity;
    
    self.infoDic[@"bankName"] = [UserInfoManager sharedManager].userClaimInput.bankName;
    
    self.infoDic[@"branch"] =[UserInfoManager sharedManager].userClaimInput.bankBranchName ;
    
    self.infoDic[@"price"] = [UserInfoManager sharedManager].userClaimInput.applyCost;
}

-(void)setupData
{
    self.keyArr = @[@"accountName",@"bankAccount",@"address",@"bankName",@"branch",@"price"];
    
    [self initInfoDic];
    
    
    
    
    
    self.titleArr = @[@"账户名",@"银行账号",@"开户城市",@"开户行",@"分行名称",@"申请金额"];
    self.picArr = @[@"ios_07.png",@"ios_16.png",@"ios_24.png",@"ios_32.png",@"ios_40.png",@"ios_47.png"];
    
    [self.infoDic setValue:[UserInfoManager sharedManager].modelMser.userName forKey:@"accountName"] ;
    
    self.branchArr =[[NSMutableArray alloc]init];
}

-(void)viewWillAppear:(BOOL)animated
{
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
}
-(void)setupView
{
    self.mainTableView.tableFooterView = self.nextView;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}
- (IBAction)nextAction:(id)sender {
    
    if (self.editingField) {
        [self.editingField resignFirstResponder];
    }
    
    for (int i=0;i<self.keyArr.count;i++)
    {
        NSString *key = self.keyArr[i];
        NSString *value = self.infoDic[key];
        if (value.length==0) {
            NSString *title = self.titleArr[i];
            [Utils showAlert:[NSString stringWithFormat:@"%@不能为空",title]];
            return;
        }
    }
    
    [UserInfoManager sharedManager].userClaimInput.bankAccountName= self.infoDic[@"accountName"];
    
    [UserInfoManager sharedManager].userClaimInput.bankAccount =self.infoDic[@"bankAccount"];
    
    [UserInfoManager sharedManager].userClaimInput.bankAccountCity =self.infoDic[@"address"];
    
    [UserInfoManager sharedManager].userClaimInput.bankName =self.infoDic[@"bankName"];
    
    [UserInfoManager sharedManager].userClaimInput.bankBranchName =self.infoDic[@"branch"];
    
    NSString *price=self.infoDic[@"price"];
    if([self isPureFloat:price]){
        if([price floatValue]>=100000000){
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"金额信息格式有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            return;
        }
        NSRange range=[price rangeOfString:@"."];
        if(range.length!=0&&price.length-1-range.location>2){
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"金额信息格式有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            return;
        }
    }else{
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"金额信息格式有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;

    }
    
    [UserInfoManager sharedManager].userClaimInput.applyCost =self.infoDic[@"price"];
    
    
    
    
    if (self.isChangeInfo) {
        [self.delegate changeBankInfo];
        [self.navigationController popViewControllerAnimated:YES];
        
    }else
    {
        //去下一个页面
        ClaimPicViewController *vc=[[ClaimPicViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
//    ClaimProgressViewController *progressVC = [[ClaimProgressViewController alloc]initWithNibName:@"ClaimProgressViewController" bundle:nil];
//    [self.navigationController pushViewController:progressVC animated:YES];
}

- (BOOL)isPureFloat:(NSString *)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    float val;
    
    return [scan scanFloat:&val] && [scan isAtEnd];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier=@"CellIdentifier";
    SelfClaimTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    [cell.titleImageView setImage:[UIImage imageNamed:self.picArr[indexPath.row]]];
    
    cell.inputTextField.delegate = self;
    
    
    
    cell.titleLabel.text =[NSString stringWithFormat:@"%@:",self.titleArr[indexPath.row]];
    cell.inputTextField.userInteractionEnabled= YES;
    cell.inputTextField.inputView = self.choicePicker;
    cell.inputTextField.tag = 200+indexPath.row;
    
    cell.actionBtn.hidden = YES;
    switch (indexPath.row) {
            //账户名
        case 0:
        {
            cell.inputTextField.text = self.infoDic[self.keyArr[indexPath.row]];
            cell.inputTextField.inputView = nil;
            cell.inputTextField.inputAccessoryView = nil;
        }
            
            
            break;
            //银行账号
            case 1:
        {
            cell.inputTextField.text =self.infoDic[self.keyArr[indexPath.row]];
            cell.inputTextField.inputView = nil;
            cell.inputTextField.inputAccessoryView = nil;
            cell.inputTextField.keyboardType = UIKeyboardTypeDecimalPad;
        }
            break;
            //开户城市
        case 2:
        {
            cell.contentLabel.text =self.infoDic[self.keyArr[indexPath.row]];
            cell.inputTextField.userInteractionEnabled = NO;
            cell.actionBtn.hidden = NO;
            [cell.actionBtn addTarget:self action:@selector(choiceAddress:) forControlEvents:64];
        }
            
            break;
            //开户行
        case 3:
        {
            cell.contentLabel.text =self.infoDic[self.keyArr[indexPath.row]];
            [cell confirmAction:^{
                NSDictionary *dic =self.bankArr [[self.choicePicker selectedRowInComponent:0]];
                
                cell.contentLabel.text = dic[@"head"];
                
                [self.infoDic setValue:dic[@"head"] forKey:@"bankName"];
                
                
            }];
        }
            break;
            //分行名称
        case 4:
        {
            cell.contentLabel.text = self.infoDic[self.keyArr[indexPath.row]];
            cell.inputTextField.userInteractionEnabled = NO;
            cell.actionBtn.hidden = NO;
            [cell.actionBtn addTarget:self action:@selector(choiceBranch:) forControlEvents:64];
            
            
        }
            break;
            //申请金额
        case 5:
        {
            cell.inputTextField.text = self.infoDic[self.keyArr[indexPath.row]];
            cell.inputTextField.inputView = nil;
            cell.inputTextField.inputAccessoryView = nil;
            cell.inputTextField.placeholder = @"0";
            cell.inputTextField.keyboardType = UIKeyboardTypeDecimalPad;
        }
            break;


        
    }
    
    return cell;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.infoDic setValue:textField.text forKey:self.keyArr[textField.tag-200]];
}

-(void)choiceBranch:(UIButton *)sender
{
    SelfClaimTableViewCell *cell =(SelfClaimTableViewCell *) sender.superview.superview;
    NSString *bank = [self.infoDic valueForKey:@"bankName"];
    if (bank!=nil&&bank.length>0) {
        ChoiceBankViewController *cbVC = [[ChoiceBankViewController alloc]initWithNibName:@"ChoiceBankViewController" bundle:nil];
        NSDictionary *dic = self.bankArr[[self.choicePicker selectedRowInComponent:0]];
        
        NSArray *dataArr = dic[@"parts"];
        
        [cbVC finishChoice:^(NSString *branchStr) {
            cell.contentLabel.text = branchStr;
            [self.infoDic setValue:branchStr forKey:@"branch"];
        }];
        
        
        [cbVC setDataArr:dataArr];
        [self.navigationController pushViewController:cbVC animated:YES];
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"请先选择开户行" maskType:SVProgressHUDMaskTypeBlack];
    }
    
    
}

#pragma mark 选择开户城市
-(void)choiceAddress:(UIButton *)sender
{
        SelfClaimTableViewCell *cell =(SelfClaimTableViewCell *) sender.superview.superview;
    SignInfoViewController *signInfoVC = [[SignInfoViewController alloc]initWithNibName:@"SignInfoViewController" bundle:nil];
    [signInfoVC setPickViewStyle:PickViewAeraThreeChoice];
    [signInfoVC finishPlaceEdit:^(NSString *nameStr, NSString *codeStr) {
        cell.contentLabel.text = nameStr;
        [self.infoDic setValue:nameStr forKey:@"address"];
        
    }];
    
    [self.navigationController pushViewController:signInfoVC animated:YES];
}


-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.editingField = textField;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
//    switch (self.pickStyle) {
//        case 1:
    
    NSDictionary *dic = self.bankArr[row];
            return dic[@"head"];
//            break;
//            case 2:
//            return self.branchArr[row];
//            break;
//    }
//    
//    return @"";
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
//    switch (self.pickStyle) {
//        case 1:
            return self.bankArr.count;
//            break;
//        case 2:
//            return self.branchArr.count;
//            break;
//    }
//    return 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
